<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 6.0.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free@5.15.3/css/all.min.css" integrity="sha256-2H3fkXt6FEmrReK448mDVGKb3WW2ZZw35gI7vqHOE4Y=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/animate.css@3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"example.com","root":"/","images":"/images","scheme":"Gemini","version":"8.7.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":true,"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"Searching...","empty":"We didn't find any results for the search: ${query}","hits_time":"${hits} results found in ${time} ms","hits":"${hits} results found"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>
<meta property="og:type" content="article">
<meta property="og:title" content="react hooks 详解">
<meta property="og:url" content="http://example.com/2021/12/11/14/index.html">
<meta property="og:site_name" content="Xiaolong&#39;s Blog">
<meta property="og:locale" content="en_US">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/Drwna/image//images/Snipaste_2021-11-29_23-27-35.png">
<meta property="og:image" content="https://cdn.jsdelivr.net/gh/Drwna/image//images/Snipaste_2021-11-29_23-27-35.png">
<meta property="article:published_time" content="2021-12-11T15:03:14.000Z">
<meta property="article:modified_time" content="2021-12-11T15:03:54.449Z">
<meta property="article:author" content="Xiaolong">
<meta property="article:tag" content="react">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://cdn.jsdelivr.net/gh/Drwna/image//images/Snipaste_2021-11-29_23-27-35.png">


<link rel="canonical" href="http://example.com/2021/12/11/14/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"en","comments":true,"permalink":"http://example.com/2021/12/11/14/","path":"2021/12/11/14/","title":"react hooks 详解"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>react hooks 详解 | Xiaolong's Blog</title>
  




  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <h1 class="site-title">Xiaolong's Blog</h1>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu">
        <li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a></li>
        <li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a></li>
        <li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>Search
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="Searching..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#useState"><span class="nav-number">1.</span> <span class="nav-text">useState</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E4%BD%BF%E7%94%A8%E7%8A%B6%E6%80%81%EF%BC%9A"><span class="nav-number">1.0.0.1.</span> <span class="nav-text">使用状态：</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B91%EF%BC%9A%E4%B8%8D%E5%8F%AF%E5%B1%80%E9%83%A8%E6%9B%B4%E6%96%B0"><span class="nav-number">1.0.0.2.</span> <span class="nav-text">注意事项1：不可局部更新</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E6%B3%A8%E6%84%8F%E4%BA%8B%E9%A1%B92%EF%BC%9A%E5%AF%B9%E8%B1%A1%E5%9C%B0%E5%9D%80%E8%A6%81%E5%8F%98"><span class="nav-number">1.0.0.3.</span> <span class="nav-text">注意事项2：对象地址要变</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useReducer"><span class="nav-number">2.</span> <span class="nav-text">useReducer</span></a><ol class="nav-child"><li class="nav-item nav-level-5"><a class="nav-link" href="#%E7%94%A8%E6%9D%A5%E8%B7%B5%E8%A1%8C-Flux-Redux-%E7%9A%84%E6%80%9D%E6%83%B3"><span class="nav-number">2.0.0.1.</span> <span class="nav-text">用来践行 Flux&#x2F;Redux 的思想</span></a></li><li class="nav-item nav-level-5"><a class="nav-link" href="#%E5%A6%82%E4%BD%95%E4%BB%A3%E6%9B%BF-Redux"><span class="nav-number">2.0.0.2.</span> <span class="nav-text">如何代替 Redux</span></a></li></ol></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useContext"><span class="nav-number">3.</span> <span class="nav-text">useContext</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useEffect"><span class="nav-number">4.</span> <span class="nav-text">useEffect</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#useLayoutEffect"><span class="nav-number">4.1.</span> <span class="nav-text">useLayoutEffect</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useMemo"><span class="nav-number">5.</span> <span class="nav-text">useMemo</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useCallback"><span class="nav-number">6.</span> <span class="nav-text">useCallback</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useRef"><span class="nav-number">7.</span> <span class="nav-text">useRef</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#forwardRef"><span class="nav-number">7.1.</span> <span class="nav-text">forwardRef</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#useImperativeHandle"><span class="nav-number">8.</span> <span class="nav-text">useImperativeHandle</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89-Hook"><span class="nav-number">9.</span> <span class="nav-text">自定义 Hook</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Stale-Closure"><span class="nav-number">10.</span> <span class="nav-text">Stale Closure</span></a></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-overview">
            <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="Xiaolong"
      src="/images/lion.jpg">
  <p class="site-author-name" itemprop="name">Xiaolong</p>
  <div class="site-description" itemprop="description">Never stop learning</div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">45</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">17</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>
  <div class="links-of-author site-overview-item animated">
      <span class="links-of-author-item">
        <a href="https://github.com/drwna" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;drwna" rel="noopener" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>



          </div>
        </div>
      </div>
        <div class="back-to-top animated" role="button" aria-label="Back to top">
          <i class="fa fa-arrow-up"></i>
          <span>0%</span>
        </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="reading-progress-bar"></div>

  <a href="https://github.com/Drwna" class="github-corner" title="Follow me on GitHub" aria-label="Follow me on GitHub" rel="noopener" target="_blank"><svg width="80" height="80" viewBox="0 0 250 250" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"></path><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"></path><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"></path></svg></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="en">
    <link itemprop="mainEntityOfPage" href="http://example.com/2021/12/11/14/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/lion.jpg">
      <meta itemprop="name" content="Xiaolong">
      <meta itemprop="description" content="Never stop learning">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Xiaolong's Blog">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react hooks 详解
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">Posted on</span>

      <time title="Created: 2021-12-11 23:03:14" itemprop="dateCreated datePublished" datetime="2021-12-11T23:03:14+08:00">2021-12-11</time>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <center><img src="https://cdn.jsdelivr.net/gh/Drwna/image//images/Snipaste_2021-11-29_23-27-35.png" alt="Snipaste_2021-11-29_23-27-35" width="800px"></center>

<span id="more"></span>

<p><a target="_blank" rel="noopener" href="https://zh-hans.reactjs.org/docs/hooks-reference.html">官方文档</a></p>
<br />

<h2 id="useState"><a href="#useState" class="headerlink" title="useState"></a>useState</h2><h5 id="使用状态："><a href="#使用状态：" class="headerlink" title="使用状态："></a>使用状态：</h5><ul>
<li><code>const[n, setN] = React.useState(0)</code></li>
<li><code>const[user, setUser] = React.useState(&#123;name:&#39;frank&#125;)</code></li>
</ul>
<h5 id="注意事项1：不可局部更新"><a href="#注意事项1：不可局部更新" class="headerlink" title="注意事项1：不可局部更新"></a>注意事项1：不可局部更新</h5><p>如果 state 是一个对象，能否只更新部分？</p>
<p>答案是不行，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/snowy-pine-7gdw2">示例代码</a></p>
<p>因为 setState 不会帮我们合并属性。</p>
<h5 id="注意事项2：对象地址要变"><a href="#注意事项2：对象地址要变" class="headerlink" title="注意事项2：对象地址要变"></a>注意事项2：对象地址要变</h5><p>setState (obj) 如果 obj 地址不变，即使数据变了，那么 React 认为 数据没有变化。</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">React</span>, &#123;useState&#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">ReactDOM</span> <span class="keyword">from</span> <span class="string">&quot;react-dom&quot;</span>;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">App</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> [user,setUser] = <span class="title function_">useState</span>(&#123;<span class="attr">name</span>:<span class="string">&#x27;Frank&#x27;</span>, <span class="attr">age</span>: <span class="number">18</span>&#125;)</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">onClick</span> = (<span class="params"></span>)=&gt;&#123;</span><br><span class="line">    <span class="comment">// 这么修改没有用</span></span><br><span class="line">    user.<span class="property">name</span> = <span class="string">&#x27;java&#x27;</span></span><br><span class="line">    <span class="title function_">setUser</span>(user)</span><br><span class="line">    <span class="comment">// 正确y</span></span><br><span class="line">    <span class="title function_">setUser</span>(&#123;</span><br><span class="line">        ...user,</span><br><span class="line">        <span class="attr">name</span>: <span class="string">&#x27;java&#x27;</span></span><br><span class="line">    &#125;)</span><br><span class="line">  &#125;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot;App&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h1</span>&gt;</span>&#123;user.name&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h2</span>&gt;</span>&#123;user.age&#125;<span class="tag">&lt;/<span class="name">h2</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;onClick&#125;</span>&gt;</span>Click<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"><span class="keyword">const</span> rootElement = <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;root&quot;</span>);</span><br><span class="line"><span class="title class_">ReactDOM</span>.<span class="title function_">render</span>(<span class="language-xml"><span class="tag">&lt;<span class="name">App</span> /&gt;</span></span>, rootElement);</span><br></pre></td></tr></table></figure>

<p>useState 接收函数</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> [state, setState] = <span class="title function_">useState</span>(<span class="function">()=&gt;</span>&#123;<span class="keyword">return</span> initialState&#125;)</span><br><span class="line">该函数返回初始 state, 且只执行一次</span><br></pre></td></tr></table></figure>

<p>setState 接收函数</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">setN</span>(<span class="function"><span class="params">i</span> =&gt;</span> i + <span class="number">1</span>)</span><br></pre></td></tr></table></figure>

<p>优先使用函数，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/suspicious-pond-le38m">demo</a></p>
<p><a target="_blank" rel="noopener" href="https://drwna.github.io/2021/11/24/51/">自定义 useState</a></p>
<br />

<h2 id="useReducer"><a href="#useReducer" class="headerlink" title="useReducer"></a>useReducer</h2><h5 id="用来践行-Flux-Redux-的思想"><a href="#用来践行-Flux-Redux-的思想" class="headerlink" title="用来践行 Flux/Redux 的思想"></a>用来践行 Flux/Redux 的思想</h5><p>共四步：</p>
<ol>
<li>创建初始值 initialState</li>
<li>创建所有操作 reduce(state, actioin)</li>
<li>传给 useReducer, 得到读和写 API</li>
<li>调用<strong>写 ({type: ‘操作类型’})</strong></li>
</ol>
<p>总的来说 useReducer 是 useState 的复杂版。</p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/tender-golick-2qxut">demo</a></p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 创建初始值</span></span><br><span class="line"><span class="keyword">const</span> initial = &#123;</span><br><span class="line">  <span class="attr">n</span>: <span class="number">0</span></span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 创建所有操作</span></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">reducer</span> = (<span class="params">state, action</span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">if</span> (action.<span class="property">type</span> === <span class="string">&quot;add&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">n</span>: state.<span class="property">n</span> + action.<span class="property">number</span> &#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> <span class="keyword">if</span> (action.<span class="property">type</span> === <span class="string">&quot;multi&quot;</span>) &#123;</span><br><span class="line">    <span class="keyword">return</span> &#123; <span class="attr">n</span>: state.<span class="property">n</span> * <span class="number">2</span> &#125;;</span><br><span class="line">  &#125; <span class="keyword">else</span> &#123;</span><br><span class="line">    <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>(<span class="string">&quot;unknown type&quot;</span>);</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">function</span> <span class="title function_">App</span>(<span class="params"></span>) &#123;</span><br><span class="line">   <span class="comment">// useReducer</span></span><br><span class="line">  <span class="keyword">const</span> [state, dispatch] = <span class="title function_">useReducer</span>(reducer, initial);</span><br><span class="line">  <span class="keyword">const</span> &#123; n &#125; = state;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">onClick</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="comment">// 调用 写 (&#123;type: ‘操作类型’&#125;) </span></span><br><span class="line">    <span class="title function_">dispatch</span>(&#123; <span class="attr">type</span>: <span class="string">&quot;add&quot;</span>, <span class="attr">number</span>: <span class="number">1</span> &#125;);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">onClick2</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="title function_">dispatch</span>(&#123; <span class="attr">type</span>: <span class="string">&quot;add&quot;</span>, <span class="attr">number</span>: <span class="number">2</span> &#125;);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span> <span class="attr">className</span>=<span class="string">&quot;App&quot;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h1</span>&gt;</span>n: &#123;n&#125;<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span></span><br><span class="line"><span class="language-xml"></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;onClick&#125;</span>&gt;</span>+1<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;onClick2&#125;</span>&gt;</span>+2<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/admiring-framework-4by2t">useReducer 表单例子</a></p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> <span class="title class_">React</span>, &#123; useReducer &#125; <span class="keyword">from</span> <span class="string">&quot;react&quot;</span>;</span><br><span class="line"><span class="keyword">import</span> <span class="title class_">ReactDOM</span> <span class="keyword">from</span> <span class="string">&quot;react-dom&quot;</span>;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> initFormData = &#123;</span><br><span class="line">  <span class="attr">name</span>: <span class="string">&quot;&quot;</span>,</span><br><span class="line">  <span class="attr">age</span>: <span class="number">18</span>,</span><br><span class="line">  <span class="attr">nationality</span>: <span class="string">&quot;汉族&quot;</span>,</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">reducer</span> = (<span class="params">state, action</span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">switch</span> (action.<span class="property">type</span>) &#123;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&quot;patch&quot;</span>:</span><br><span class="line">      <span class="keyword">return</span> &#123; ...state, ...action.<span class="property">formData</span> &#125;;</span><br><span class="line">    <span class="keyword">case</span> <span class="string">&quot;reset&quot;</span>:</span><br><span class="line">      <span class="keyword">return</span> initFormData;</span><br><span class="line">    <span class="attr">default</span>:</span><br><span class="line">      <span class="keyword">throw</span> <span class="keyword">new</span> <span class="title class_">Error</span>();</span><br><span class="line">  &#125;</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> <span class="title function_">App</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;aaa&quot;</span>);</span><br><span class="line">  <span class="keyword">const</span> [formData, dispatch] = <span class="title function_">useReducer</span>(reducer, initFormData);</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">onSubmit</span> = (<span class="params"></span>) =&gt; &#123;&#125;;</span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">onReset</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="title function_">dispatch</span>(&#123; <span class="attr">type</span>: <span class="string">&quot;reset&quot;</span> &#125;);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">form</span> <span class="attr">onSubmit</span>=<span class="string">&#123;onSubmit&#125;</span> <span class="attr">onReset</span>=<span class="string">&#123;onReset&#125;</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">          姓名</span></span><br><span class="line"><span class="language-xml">          <span class="tag">&lt;<span class="name">input</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">value</span>=<span class="string">&#123;formData.name&#125;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">onChange</span>=<span class="string">&#123;(e)</span> =&gt;</span></span></span><br><span class="line"><span class="language-xml">              dispatch(&#123;</span></span><br><span class="line"><span class="language-xml">                type: &quot;patch&quot;,</span></span><br><span class="line"><span class="language-xml">                formData: &#123; name: e.target.value &#125;,</span></span><br><span class="line"><span class="language-xml">              &#125;)</span></span><br><span class="line"><span class="language-xml">            &#125;</span></span><br><span class="line"><span class="language-xml">          /&gt;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">          年龄</span></span><br><span class="line"><span class="language-xml">          <span class="tag">&lt;<span class="name">input</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">value</span>=<span class="string">&#123;formData.age&#125;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">onChange</span>=<span class="string">&#123;(e)</span> =&gt;</span></span></span><br><span class="line"><span class="language-xml">              dispatch(&#123;</span></span><br><span class="line"><span class="language-xml">                type: &quot;reset&quot;,</span></span><br><span class="line"><span class="language-xml">                formData: &#123; age: e.target.name &#125;,</span></span><br><span class="line"><span class="language-xml">              &#125;)</span></span><br><span class="line"><span class="language-xml">            &#125;</span></span><br><span class="line"><span class="language-xml">          /&gt;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">          民族</span></span><br><span class="line"><span class="language-xml">          <span class="tag">&lt;<span class="name">input</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">value</span>=<span class="string">&#123;formData.nationality&#125;</span></span></span></span><br><span class="line"><span class="tag"><span class="language-xml">            <span class="attr">onChange</span>=<span class="string">&#123;(e)</span> =&gt;</span></span></span><br><span class="line"><span class="language-xml">              dispatch(&#123;</span></span><br><span class="line"><span class="language-xml">                type: &quot;patch&quot;,</span></span><br><span class="line"><span class="language-xml">                formData: &#123; nationality: e.target.value &#125;,</span></span><br><span class="line"><span class="language-xml">              &#125;)</span></span><br><span class="line"><span class="language-xml">            &#125;</span></span><br><span class="line"><span class="language-xml">          /&gt;</span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;/<span class="name">label</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;submit&quot;</span>&gt;</span>提交<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">button</span> <span class="attr">type</span>=<span class="string">&quot;reset&quot;</span>&gt;</span>重置<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">hr</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      &#123;JSON.stringify(formData)&#125;</span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">form</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br><span class="line"></span><br><span class="line"><span class="title class_">ReactDOM</span>.<span class="title function_">render</span>(<span class="language-xml"><span class="tag">&lt;<span class="name">App</span> /&gt;</span></span>, <span class="variable language_">document</span>.<span class="title function_">getElementById</span>(<span class="string">&quot;root&quot;</span>));</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<br />

<h5 id="如何代替-Redux"><a href="#如何代替-Redux" class="headerlink" title="如何代替 Redux"></a>如何代替 Redux</h5><p>步骤：</p>
<ol>
<li>将数据集中在一个 store 对象</li>
<li>将所有操作集中在 reducer</li>
<li>创建一个 Context</li>
<li>创建对数据的读写 API</li>
<li>将第四步的内容放到第三步的 Context</li>
<li>用 Context.Provider 将 Context 提供给所有组件</li>
<li>各个组件用 useContext 获取读写 API</li>
</ol>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/interesting-volhard-lfxpm">demo</a> ，模块化后 <a target="_blank" rel="noopener" href="https://codesandbox.io/s/priceless-jennings-gyls6">demo</a></p>
<br />

<h2 id="useContext"><a href="#useContext" class="headerlink" title="useContext"></a>useContext</h2><p>上下文</p>
<p>全局变量是全局的上下文</p>
<p>上下文是局部的全局变量</p>
<p>使用：</p>
<ol>
<li>使用 <code>C = createContext(initial)</code> 创建上下文</li>
<li>使用 <code>&lt;C.provider&gt;</code> 圈定作用域</li>
<li>在作用域内使用 <code>useContext(C)</code> 来使用上下文</li>
</ol>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/elated-hill-9rkug">demo</a></p>
<p>注意：</p>
<p>useContext 不是响应式的。</p>
<p>在一个模块将 C 里的值改变，另一个模块不会感知到这个变化。</p>
<br />

<h2 id="useEffect"><a href="#useEffect" class="headerlink" title="useEffect"></a>useEffect</h2><p>副作用</p>
<ul>
<li>对环境的改变即为副作用，如修改 document.title</li>
<li>但我们不一定非要把副作用放在 useEffect 里</li>
<li>实际上叫做 afterRender 更好，因为每次 render 后会执行</li>
</ul>
<p>用途：</p>
<ul>
<li>作为 componentDidMount 使用， [] 作第二个参数</li>
<li>作为 componentDidUpdate 使用，可指定依赖</li>
<li>作为 componentWillUnmount 使用，通过 return</li>
<li>以上三种用途可同时存在</li>
</ul>
<p>特点：如果同时存在多个 useEffect，会按照出现次序执行。</p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/black-butterfly-79g62?file=/src/index.js">demo</a></p>
<h3 id="useLayoutEffect"><a href="#useLayoutEffect" class="headerlink" title="useLayoutEffect"></a>useLayoutEffect</h3><p>布局副作用</p>
<p>useEffect 在浏览器渲染完成后执行，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/useeffect-flash-on-render-forked-d1poj?file=/src/index.js">demo</a></p>
<p>useLayoutEffect 在浏览器渲染前执行，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/charming-sammet-xcwkr">通过时间点来侧面证明</a></p>
<p>特点：</p>
<p>useLayoutEffect 总是比 useEffect 先执行，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/beautiful-hill-1or8e">demo</a></p>
<p>useLayoutEffect 里的任务最好影响了 Layout，不然没必要用 useLayoutEffect。</p>
<p>经验：</p>
<p>为了用户体验，优先使用 useEffect（优先渲染）</p>
<br />

<h2 id="useMemo"><a href="#useMemo" class="headerlink" title="useMemo"></a>useMemo</h2><p>要理解 React.useMemo，需要先了解 React.memo，React 默认有多余的 render，<a target="_blank" rel="noopener" href="https://codesandbox.io/s/gracious-villani-k3ms0">demo</a>，代码中的 Child 用 React.memo(Child)代替，如果 props 不变，就不会再次执行函数组件。</p>
<p>useMemo 的作用就是提供了一个 memorize 值，在依赖项改变之后，该值才会改变才会被重新计算。<a target="_blank" rel="noopener" href="https://codesandbox.io/s/bold-sunset-g9136">demo</a></p>
<p>特点：</p>
<ul>
<li><p>第一个参数是 <code>()=&gt;value</code></p>
</li>
<li><p>第二个参数是依赖 <code>[m, n]</code></p>
</li>
</ul>
<p>只有当依赖变化时，才会计算出新的 value，如果依赖不变，那么就重用之前的 value。类似于 vue2 的 computed。</p>
<p>注意：如果 value 是个函数，那么就要写成 <code>useMemo( ()=&gt; (x)=&gt;console.log(&#39;1&#39;) )</code>，这是一个返回函数的函数，</p>
<p>于是就有了 useCallback，<code>useCallback( (x)=&gt;console.log(&#39;1&#39;) )</code></p>
<br />

<h2 id="useCallback"><a href="#useCallback" class="headerlink" title="useCallback"></a>useCallback</h2><p>用法：</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="title function_">useCallback</span>(<span class="function"><span class="params">x</span> =&gt;</span> <span class="variable language_">console</span>.<span class="title function_">log</span>(x), [m])</span><br><span class="line">等价于</span><br><span class="line"><span class="title function_">useMemo</span>( <span class="function">() =&gt;</span> <span class="function"><span class="params">x</span>=&gt;</span><span class="variable language_">console</span>.<span class="title function_">log</span>(x), [m])</span><br></pre></td></tr></table></figure>

<br />

<h2 id="useRef"><a href="#useRef" class="headerlink" title="useRef"></a>useRef</h2><p>目的：</p>
<p>如果你需要一个值，在组件不断 render 时<strong>保持不变</strong></p>
<p>初始化：<code>const count = useRef(0)</code>，<a target="_blank" rel="noopener" href="https://github.com/Drwna/react-demo/blob/f254a704441469d57458d56a3367264d0165e96e/src/index.js#L6">code</a></p>
<p>读取：<code>count.current</code></p>
<p>为什么需要 current ?</p>
<p> 为了保证两次 useRef 是同一个值（只有引用能做到）</p>
<p>useRef 不会自动更新 UI。</p>
<p>拓展：</p>
<p><a target="_blank" rel="noopener" href="https://v3.vuejs.org/api/refs-api.html#refs">vue3 的 ref，</a></p>
<p>初始化：<code>const count = ref(0)</code></p>
<p>读取：<code>count.value</code></p>
<p>不同点：Vue3 会自动 render。</p>
<h3 id="forwardRef"><a href="#forwardRef" class="headerlink" title="forwardRef"></a>forwardRef</h3><p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/snowy-dust-g9i0w">demo1</a>：props 无法传递 ref 属性</p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/crazy-matsumoto-6l6mh">demo2</a>：实现 ref 的传递</p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/amazing-snow-9f5g3">demo3</a>：两次 ref 传递得到 button 的引用</p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">const</span> <span class="title function_">App</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">  <span class="keyword">const</span> buttonRef = <span class="title function_">useRef</span>(<span class="literal">null</span>);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">&quot;buttonRef&quot;</span>, buttonRef);</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">h1</span>&gt;</span>React.forwardRef<span class="tag">&lt;/<span class="name">h1</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">hr</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">        <span class="tag">&lt;<span class="name">Button3</span> <span class="attr">ref</span>=<span class="string">&#123;buttonRef&#125;</span>&gt;</span>button<span class="tag">&lt;/<span class="name">Button3</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;;</span><br><span class="line"><span class="keyword">const</span> <span class="title function_">Button2</span> = (<span class="params">props, ref</span>) =&gt; &#123;</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(props);</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(ref);</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">button</span> <span class="attr">className</span>=<span class="string">&quot;red&quot;</span> <span class="attr">ref</span>=<span class="string">&#123;ref&#125;</span> &#123;<span class="attr">...props</span>&#125; /&gt;</span></span>;</span><br><span class="line">&#125;;</span><br><span class="line"><span class="comment">// 实现 ref 的传递</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">Button3</span> = <span class="title function_">forwardRef</span>(<span class="title class_">Button2</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// const Button4 = forwardRef((props, ref) =&gt; &#123;</span></span><br><span class="line"><span class="comment">//   console.log(props);</span></span><br><span class="line"><span class="comment">//   console.log(ref);</span></span><br><span class="line"><span class="comment">//   return &lt;button className=&quot;red&quot; ref=&#123;ref&#125; &#123;...props&#125; /&gt;;</span></span><br><span class="line"><span class="comment">// &#125;);</span></span><br></pre></td></tr></table></figure>



<p>useRef：</p>
<ul>
<li>可以用来引用 DOM 对象</li>
<li>也可以用来引用 普通对象</li>
</ul>
<p>forwardRef：</p>
<ul>
<li>由于 props 不包含 ref，所以需要 forwardRef</li>
<li>为生命 props 不包含 ref ？以为大部分时候不需要。</li>
</ul>
<br />

<h2 id="useImperativeHandle"><a href="#useImperativeHandle" class="headerlink" title="useImperativeHandle"></a>useImperativeHandle</h2><p>用于自定义 ref 的属性。<a target="_blank" rel="noopener" href="https://github.com/puxiao/react-hook-tutorial/blob/master/13%20useImperativeHandle%E5%9F%BA%E7%A1%80%E7%94%A8%E6%B3%95.md">推荐阅读</a></p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/awesome-goldwasser-v7vsp">demo1 使用 useImperativeHandle</a></p>
<p><a target="_blank" rel="noopener" href="https://codesandbox.io/s/elegant-poitras-mxoym">demo2 不使用 useImperativeHandle</a></p>
<figure class="highlight jsx"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">// 子组件</span></span><br><span class="line"><span class="keyword">const</span> <span class="title class_">ChildComponent</span> = <span class="title function_">forwardRef</span>(<span class="function">(<span class="params">props, ref</span>) =&gt;</span> &#123;</span><br><span class="line">  <span class="keyword">const</span> [count, setCount] = <span class="title function_">useState</span>(<span class="number">0</span>); <span class="comment">//子组件定义内部变量count</span></span><br><span class="line">  <span class="comment">//子组件定义内部函数 addCount</span></span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">addCount</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    <span class="title function_">setCount</span>(count + <span class="number">1</span>);</span><br><span class="line">  &#125;;</span><br><span class="line">  <span class="comment">//子组件通过useImperativeHandle函数，将addCount函数添加到父组件中的ref.current中</span></span><br><span class="line">  <span class="title function_">useImperativeHandle</span>(ref, <span class="function">() =&gt;</span> (&#123; addCount &#125;));</span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      &#123;count&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;addCount&#125;</span>&gt;</span>child<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 父组件</span></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Imperative</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">const</span> childRef = <span class="title function_">useRef</span>(<span class="literal">null</span>); <span class="comment">//父组件定义一个对子组件的引用</span></span><br><span class="line"></span><br><span class="line">  <span class="keyword">const</span> <span class="title function_">clickHandle</span> = (<span class="params"></span>) =&gt; &#123;</span><br><span class="line">    childRef.<span class="property">current</span>.<span class="title function_">addCount</span>(); <span class="comment">//父组件调用子组件内部 addCount函数</span></span><br><span class="line">  &#125;;</span><br><span class="line"></span><br><span class="line">  <span class="keyword">return</span> (</span><br><span class="line">    <span class="language-xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">      &#123;/* 父组件通过给子组件添加 ref 属性，将childRef传递给子组件，</span></span><br><span class="line"><span class="language-xml">            子组件获得该引用即可将内部函数添加到childRef中 */&#125;</span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">ChildComponent</span> <span class="attr">ref</span>=<span class="string">&#123;childRef&#125;</span> /&gt;</span></span></span><br><span class="line"><span class="language-xml">      <span class="tag">&lt;<span class="name">button</span> <span class="attr">onClick</span>=<span class="string">&#123;clickHandle&#125;</span>&gt;</span>child component do something<span class="tag">&lt;/<span class="name">button</span>&gt;</span></span></span><br><span class="line"><span class="language-xml">    <span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">  );</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">App</span>(<span class="params"></span>) &#123;</span><br><span class="line">  <span class="keyword">return</span> <span class="language-xml"><span class="tag">&lt;<span class="name">Imperative</span> /&gt;</span></span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<br />

<h2 id="自定义-Hook"><a href="#自定义-Hook" class="headerlink" title="自定义 Hook"></a>自定义 Hook</h2><p>封装数据操作</p>
<p>简单例子，贴心例子</p>
<p>还可以在自定义 Hook 里使用 Context</p>
<p>useState 只说了不能在 if 里，没说不能在函数里运行，只要这个函数在函数组件里运行即可。</p>
<h2 id="Stale-Closure"><a href="#Stale-Closure" class="headerlink" title="Stale Closure"></a>Stale Closure</h2><p>过时闭包</p>
<p>参考<a target="_blank" rel="noopener" href="https://dmitripavlutin.com/react-hooks-stale-closures/">文章链接</a></p>
<br />



<center><img src="https://cdn.jsdelivr.net/gh/Drwna/image//images/Snipaste_2021-11-29_23-27-35.png" alt="Snipaste_2021-11-29_23-27-35"></center>




















    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react/" rel="tag"><i class="fa fa-tag"></i> react</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2021/11/24/39/" rel="prev" title="react类组件">
                  <i class="fa fa-chevron-left"></i> react类组件
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2022/01/16/26/" rel="next" title="Web性能优化常见技巧">
                  Web性能优化常见技巧 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 2021 – 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">Xiaolong</span>
</div>

    </div>
  </footer>

  
  <script src="https://cdn.jsdelivr.net/npm/animejs@3.2.1/lib/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script>

  
<script src="/js/third-party/search/local-search.js"></script>




  





</body>
</html>
